package by.msokoloff.javaweb2015.webapp.page.flight;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AbstractAutoCompleteRenderer;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.extensions.yui.calendar.DateTimeField;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.Response;

import by.msokoloff.javaweb2015.datamodel.Airport;
import by.msokoloff.javaweb2015.datamodel.Flight;
import by.msokoloff.javaweb2015.datamodel.Plane;
import by.msokoloff.javaweb2015.datamodel.enums.FlightStatus;
import by.msokoloff.javaweb2015.services.AirportService;
import by.msokoloff.javaweb2015.services.FlightService;
import by.msokoloff.javaweb2015.services.PlaneService;
import by.msokoloff.javaweb2015.webapp.page.EntityListPage;

public class FlightForm extends Form<Flight> {

	@Inject
	private FlightService flightService;

	@Inject
	private PlaneService planeService;

	@Inject
	private AirportService airportService;

	private Flight flight;

	public FlightForm(String id, IModel<Flight> model) {
		super(id, model);

		flight = model.getObject();

		AbstractAutoCompleteRenderer<Airport> autoCompleteRenderer = new AbstractAutoCompleteRenderer<Airport>() {

			@Override
			protected final String getTextValue(final Airport airport) {
				return airport.getName() + " (" + airport.getId() + ")";
			}

			@Override
			protected final void renderChoice(final Airport airport, final Response response, final String criteria) {
				response.write(getTextValue(airport));
			}

		};

		AutoCompleteTextField<Airport> actfFrom = new AutoCompleteTextField<Airport>("departureAirport", new Model<Airport>(), autoCompleteRenderer) {

			@Override
			protected Iterator<Airport> getChoices(String input) {

				if (input.length() < 3) {
					List<Airport> emptyList = new ArrayList<Airport>();
					return emptyList.iterator();
				}

				return airportService.getContaining(input, 20).iterator();
			}

		};

		AutoCompleteTextField<Airport> actfTo = new AutoCompleteTextField<Airport>("destinationAirport", new CompoundPropertyModel<Airport>(new Airport()), autoCompleteRenderer) {

			@Override
			protected Iterator<Airport> getChoices(String input) {

				if (input.length() < 3) {
					List<Airport> emptyList = new ArrayList<Airport>();
					return emptyList.iterator();
				}

				return airportService.getContaining(input, 20).iterator();
			}

		};

		actfFrom.add(new AjaxFormComponentUpdatingBehavior("change") {

			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				System.out.println(actfFrom.getValue());
				String s = actfFrom.getValue();
				Pattern p = Pattern.compile("^(.*)\\s\\((\\d+)\\)$");
				Matcher m = p.matcher(s);
				flight.setDepartureAirport(null);
				if (m.matches()) {
					String name = m.group(1);
					Integer id = Integer.parseInt(m.group(2));
					Airport a = airportService.get(id);
					if (name.equals(a.getName())) {
						flight.setDepartureAirport(a);
					}
				}
			}
		});

		actfTo.add(new AjaxFormComponentUpdatingBehavior("change") {

			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				String s = actfTo.getValue();
				Pattern p = Pattern.compile("^(.*)\\s\\((\\d+)\\)$");
				Matcher m = p.matcher(s);
				flight.setDestinationAirport(null);
				if (m.matches()) {
					String name = m.group(1);
					Integer id = Integer.parseInt(m.group(2));
					Airport a = airportService.get(id);
					if (name.equals(a.getName())) {
						flight.setDestinationAirport(a);
					}
				}
			}

		});

		add(new Label("id"));
		add(new TextField<String>("flightNumber"));
		add(actfFrom);
		add(actfTo);
		add(new DateTimeField("departureDate"));
		add(new DropDownChoice<Plane>("plane", planeService.getAll()));
		add(new TextField<Double>("distance"));
		add(new TextField<Integer>("duration"));
		add(new TextField<BigDecimal>("tariff"));
		add(new DropDownChoice<FlightStatus>("status", new ArrayList<FlightStatus>(Arrays.asList(FlightStatus.values()))));

		add(new FeedbackPanel("feedbackpanel"));

	}

	@Override
	public final void onSubmit() {
		flightService.createOrUpdate(flight);
		setResponsePage(new EntityListPage(Flight.class));
	}

	@Override
	public final void onError() {
		System.out.println("Error!");
	}
}
